package com.tanhua.back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.back.Dto.PageResult;
import com.tanhua.back.entity.Log;
import com.tanhua.back.entity.UserInfo;
import com.tanhua.back.mapper.UserInfoMapper;
import com.tanhua.back.service.LogService;
import com.tanhua.back.service.MessagesService;

import com.tanhua.back.vo.LogVo;
import com.tanhua.back.vo.MessagesVo;
import com.tanhua.back.vo.Totals;
import com.tanhua.model.domain.mongodb.Movement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * @author JavaClimber
 * @version 1.0
 * @date 2022/5/16 0016 zihao
 */
@Service
public class MessagesServiceImpl implements MessagesService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private LogService logService;


    @Override
    public void pass(String[] ids) {

        for (String id : ids) {
            Query query = Query.query(Criteria.where("id").is(id));
            Update update = new Update();
            update.set("state", 3);
            mongoTemplate.updateFirst(query, update, Movement.class);
        }
    }

    @Override
    public void messagesReject(String[] userId) {
        for (String id : userId) {
            Query query = Query.query(Criteria.where("id").is(id));
            Update update = new Update();
            update.set("state", 4);
            mongoTemplate.updateFirst(query, update, Movement.class);
        }
    }

    //消息置顶
    @Override
    public void MessageTop(Long id) {
        Query query = Query.query(Criteria.where("pid").is(id));
        Update update = new Update();
        update.set("topState", 2);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    //消息取消置顶
    @Override
    public void MessageUntop(Long id) {
        Query query = Query.query(Criteria.where("pid").is(id));
        Update update = new Update();
        update.set("topState", 1);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    @Override
    public MessagesVo getMessageById(String messageId) {
        Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("id").is(messageId)), Movement.class);
        MessagesVo vo = new MessagesVo();
        //获取用户的信息
        UserInfo userInfo = userInfoMapper.selectById(movement.getUserId());
        vo.setId(movement.getPid().toString());
        vo.setNickname(userInfo.getNickname());
        vo.setUserId(Convert.toInt(userInfo.getId()));
        vo.setCreateDate(Convert.toInt(movement.getCreated()));
        vo.setText(movement.getTextContent());
        vo.setState(movement.getState().toString());
        vo.setReportCount(0);
        Integer likeCount = movement.getLikeCount();
        if (ObjectUtil.isEmpty(likeCount)) {
            vo.setLikeCount(0);
        } else {
            vo.setLikeCount(likeCount);
        }
        Integer commentCount = movement.getCommentCount();
        if (ObjectUtil.isEmpty(commentCount)) {
            vo.setCommentCount(0);
        } else {
            vo.setCommentCount(commentCount);
        }

        vo.setForwardingCount(0);
        vo.setMedias(movement.getMedias());

        if (ObjectUtil.isEmpty(movement.getTopState())) {
            vo.setTopState(1);
        } else {
            vo.setTopState(movement.getTopState());
        }
        vo.setUserLogo(userInfo.getAvatar());
        return vo;
    }

    @Override
    public PageResult PageList(String uid, Integer page, Integer pagesize, String sortProp, String sortOrder, String id, Long sd, Long ed, String state) {
        List<Movement> movements = new ArrayList<>();
        Pageable pageable = PageRequest.of(page - 1, pagesize);
        Long count = 0L;
        Criteria c1 = new Criteria();
        Criteria c2 = new Criteria();
        Criteria c3 = new Criteria();
        Criteria c4 = new Criteria();
        if (StrUtil.isNotBlank(uid)) {
            c1 = Criteria.where("userId").is(Convert.toLong(uid));
        }
        if (StrUtil.isNotBlank(id)) {
            c2 = Criteria.where("userId").is(Convert.toLong(id));
        }
        if (sd != null && ed != null) {
            if (sd >= 0 && ed >= 0 && ed >= sd) {
                c3 = Criteria.where("created").gte(sd).lte(ed);
            }
        }
        if (StrUtil.isNotBlank(state)) {
            if (!StrUtil.equals("all", state)) {
                c4 = Criteria.where("state").is(Integer.parseInt(state));
            }
        }
        Query query = new Query();
        query.addCriteria(new Criteria().andOperator(c1, c2, c3, c4));
        //升序
        if (StringUtils.pathEquals(sortOrder, "ascending")) {
            if (StringUtils.pathEquals(sortProp, "createDate")) {
                //movements = mongoTemplate.find(Query.query(c).with(pageable).with(Sort.by(Sort.Order.asc("created"))).with(Sort.by(Sort.Order.desc("topState"))), Movement.class);
                movements = mongoTemplate.find(query.with(pageable).with(Sort.by(Sort.Order.desc("created"), Sort.Order.desc("topState"))), Movement.class);
                count = mongoTemplate.count(query, Movement.class);
            } else {
                //movements = mongoTemplate.find(Query.query(c).with(pageable).with(Sort.by(Sort.Order.asc(sortProp))).with(Sort.by(Sort.Order.desc("topState"))), Movement.class);
                movements = mongoTemplate.find(query.with(pageable).with(Sort.by(Sort.Order.asc(sortProp), Sort.Order.desc("topState"))), Movement.class);
                count = mongoTemplate.count(query, Movement.class);
            }

        } else if (StringUtils.pathEquals(sortOrder, "descending")) {
            //降序排列
            if (StringUtils.pathEquals(sortProp, "createDate")) {
                //movements = mongoTemplate.find(Query.query(c).with(pageable).with(Sort.by(Sort.Order.desc("created"))).with(Sort.by(Sort.Order.desc("topState"))), Movement.class);
                movements = mongoTemplate.find(query.with(pageable).with(Sort.by(Sort.Order.desc("created"), Sort.Order.desc("topState"))), Movement.class);
                count = mongoTemplate.count(query, Movement.class);
            } else {
                //movements = mongoTemplate.find(Query.query(c).with(pageable).with(Sort.by(Sort.Order.desc(sortProp))).with(Sort.by(Sort.Order.desc("topState"))), Movement.class);
                movements = mongoTemplate.find(query.with(pageable).with(Sort.by(Sort.Order.desc(sortProp), Sort.Order.desc("topState"))), Movement.class);
                count = mongoTemplate.count(query, Movement.class);

            }
        }


        List<MessagesVo> messagesVos = new ArrayList<>();
        for (Movement movement : movements) {
            //首先获取用户的信息
            Long userId = movement.getUserId();
            UserInfo userInfo = userInfoMapper.selectById(userId);
            MessagesVo vo = new MessagesVo();
            vo.setId(movement.getId().toString());
            vo.setNickname(userInfo.getNickname());
            vo.setUserId(Convert.toInt(userId));
            vo.setCreateDate(Convert.toInt(movement.getCreated()));
            vo.setText(movement.getTextContent());
            vo.setState(movement.getState().toString());
            vo.setReportCount(0);
            vo.setUserLogo(userInfo.getAvatar());
            vo.setTopState(movement.getTopState());
            Integer likeCount = movement.getLikeCount();
            if (ObjectUtil.isEmpty(likeCount)) {
                vo.setLikeCount(0);
            } else {
                vo.setLikeCount(likeCount);
            }
            Integer commentCount = movement.getCommentCount();
            if (ObjectUtil.isEmpty(commentCount)) {
                vo.setCommentCount(0);
            } else {
                vo.setCommentCount(commentCount);
            }

            vo.setForwardingCount(0);
            vo.setMedias(movement.getMedias());
            messagesVos.add(vo);
        }
        //Long count = 0L;
        List<Totals> totals = new ArrayList<>();
        //查询全部的动态
        Totals all = new Totals();
        all.setTitle("全部");
        all.setCode("all");
        //查询动态的所有数量
        Query query1 = new Query();
        Long allCount = mongoTemplate.count(query1, Movement.class);
        all.setValue(Convert.toInt(allCount));
        totals.add(all);
        //查询待审核的动态
        Totals wait = new Totals();
        wait.setTitle("待审核");
        wait.setCode("3");
        //查询待审核的动态的所有数量
        long waitCount = mongoTemplate.count(Query.query(Criteria.where("state").is(3)), Movement.class);
        if (ObjectUtil.isEmpty(waitCount)) {
            wait.setValue(0);
        } else {
            wait.setValue(Convert.toInt(waitCount));
        }
        totals.add(wait);
        //查询已通过的动态
        Totals pass = new Totals();
        pass.setTitle("已通过");
        pass.setCode("5");
        //查询已通过的动态的所有数量
        long passCount = mongoTemplate.count(Query.query(Criteria.where("state").is(5)), Movement.class);
        if (ObjectUtil.isEmpty(pass)) {
            pass.setValue(0);
        } else {
            pass.setValue(Convert.toInt(passCount));
        }

        totals.add(pass);
        //查询已驳回的动态
        Totals reject = new Totals();
        reject.setTitle("已驳回");
        reject.setCode("4");
        //查询已驳回的动态的所有数量
        long rejectCount = mongoTemplate.count(Query.query(Criteria.where("state").is(4)), Movement.class);
        if (ObjectUtil.isEmpty(rejectCount)) {
            reject.setValue(0);
        } else {
            reject.setValue(Convert.toInt(rejectCount));
        }
        totals.add(reject);
        /*if (StrUtil.equals("all", state)) {
            count = allCount;
        } else if (StrUtil.equals("3", state)) {
            count = waitCount;
        } else if (StrUtil.equals("4", state)) {
            count = rejectCount;
        } else if (StrUtil.equals("5", state)) {
            count = passCount;
        }*/
        return new PageResult(page, pagesize, Convert.toInt(count), messagesVos, totals);
    }

    @Override
    public String messagesRevocation(String[] movementIds) {
        for (String s : movementIds) {
            Query query = Query.query(Criteria.where("id").is(s));
            Update update = new Update();
            update.set("state", 3);
            mongoTemplate.updateFirst(query, update, Movement.class);

        }
        return "操作成功";
    }

    /**
     * 查看用户登录日志
     *
     * @param uid
     * @param page
     * @param pagesize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    @Override
    public PageResult findLogsByPage(Long uid, Integer page, Integer pagesize, String sortProp, String sortOrder) {
        //设置分页参数
        PageResult pr = new PageResult();
        String type = "01";
        Page iPage = logService.getPage(uid, page, pagesize, type);
        //将数据进行转化
        List<Log> logs = iPage.getRecords();
        List<LogVo> logVos = new ArrayList<>();
        for (Log log : logs) {
            LogVo vo = new LogVo();
            BeanUtil.copyProperties(log, vo);
            logVos.add(vo);
        }
        pr.setPage(page);
        pr.setCounts(Convert.toInt(iPage.getTotal()));
        pr.setItems(logVos);
        pr.setPagesize(pagesize);
        return pr;
    }
}
